from loguru import logger

from com.arcfox.middleware import async_mysql_middleware as db
from com.arcfox.util import date
from com.arcfox.util.config_parser import Config


class YiQingTask:

    def __init__(self):
        self.config = Config("yiqing.conf")

    async def pull_city_code_task(self):
        sql = "select lastupdate_time from af_city_info order by id desc limit 1"
        result = await db.query_one(sql)
        if result:
            old_date = date.parse_date(str(result[0]), date.FORMAT_DATE_NORMAL)
            update_frequency = self.config.get("city_code_update_frequency")
            if not update_frequency:
                return True
            time_different = date.get_time_different(old_date, date.now(), self.conf_unit_convertor(update_frequency))
            reach_update_time = time_different >= int(update_frequency[:-1])
            if not reach_update_time:
                logger.info(f"距离上次更新时间不超过{update_frequency}, 不更新!")
            return reach_update_time
        return True

    async def pull_risk_area_task(self):
        sql = "select lastupdate_time from af_risk_area order by id desc limit 1"
        result = await db.query_one(sql)
        if result:
            old_date = date.parse_date(str(result[0]), date.FORMAT_DATE_NORMAL)
            update_frequency = self.config.get("risk_area_update_frequency")
            if not update_frequency:
                return True
            time_different = date.get_time_different(old_date, date.now(), self.conf_unit_convertor(update_frequency))
            reach_update_time = time_different >= int(update_frequency[:-1])
            if not reach_update_time:
                logger.info(f"距离上次更新时间不超过{update_frequency}, 不更新!")
            return reach_update_time

        return True


    def conf_unit_convertor(self, update_frequency):
        conf_unit = update_frequency[-1:]
        if conf_unit.lower() == 'd':
            return date.TimeUnit.DAY
        elif conf_unit.lower() == 'h':
            return date.TimeUnit.HOUR
        elif conf_unit.lower() == 'm':
            return date.TimeUnit.MINUTE
        elif conf_unit.lower() == 's':
            return date.TimeUnit.SECOND
        else:
            raise Exception("配置错误")
